package com.mes.handler.plan;

import com.basis.utils.HibernateDao;
import com.mes.data.*;
import com.mes.manufacture.data.*;
import com.mes.plan.data.EmespPlanOrder;
import com.wms.entity.WmsSalesOrderInfo;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.base.exception.OBException;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import org.openbravo.model.common.plm.Product;
import org.openbravo.model.common.uom.UOM;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 计划订单下发
 * @author zt
 */
public class PlanOrderIssuedHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			OBContext.setAdminMode();
			JSONObject jsonData = new JSONObject(data);
			String []ids = jsonData.getString("ids").split(",");
			User user = OBDal.getInstance().get(User.class, SessionInfo.getUserId());

			EmespPlanOrder planOrder = null;
			for (String id : ids) {
				planOrder = OBDal.getInstance().get(EmespPlanOrder.class, id);
				planOrder.setStatus("RELEASE");//状态修改为已下发
				planOrder.setCheckDate(new Date());
				planOrder.setCheckUser(user);

				OBDal.getInstance().save(planOrder);
				createManuOrder(planOrder, planOrder.getQty());
			}

			jsonRep.put("msg", "计划订单下发成功");
			jsonRep.put("result", true);
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			logger.error("计划订单下发：", e);
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", "处理失败！");
			} catch (JSONException e1) {
			}
			throw new OBException(e);
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}

	/**
	 * 创建生产订单
	 * @param planOrder
	 */
	public void createManuOrder(EmespPlanOrder planOrder, BigDecimal qty) {
		EmesoManuOrder manuOrder = new EmesoManuOrder();

		manuOrder.setEmespPlanorder(planOrder);
		manuOrder.setProduct(planOrder.getProduct());
		manuOrder.setQty(qty);
		manuOrder.setCode(planOrder.getCode());
		manuOrder.setFootSizeCode(planOrder.getEmesSize().getCode());
		manuOrder.setStatus("CREATE");
		manuOrder.setUom(planOrder.getProduct().getUOM());
		manuOrder.setWmsSalesOrder(planOrder.getWmsSalesOrderDetail().getWmsSalesOrder());
		manuOrder.setPauseDate(planOrder.getReqDate());
		manuOrder.setDescription(planOrder.getDescription());

		OBDal.getInstance().save(manuOrder);

		createManuOrderBom(planOrder, manuOrder);

		createManuOrderDiy(planOrder, manuOrder);

		createManuOrderProcess(planOrder, manuOrder);

		createManuOrderJobPlan(planOrder, manuOrder);
	}

	/**
	 * 生成生产订单BOM
	 */
	private void createManuOrderBom(EmespPlanOrder planOrder, EmesoManuOrder manuOrder) {
		List<Map<String, Object>> bomList = this.getPlanOrderBomList(planOrder.getId());
		EmesoManuOrderBom manuBom = null;

		for (Map<String, Object> bom : bomList) {
			manuBom = new EmesoManuOrderBom();

			manuBom.setEmesoManuorder(manuOrder);

			if(bom.get("emes_component_id") != null){
				manuBom.setEmesComponent(OBDal.getInstance().get(EmesComponent.class, bom.get("emes_component_id")));
			}
			manuBom.setProduct(OBDal.getInstance().get(Product.class, bom.get("m_product_id")));
			if (bom.get("emes_color_id") != null) {
				manuBom.setEmesColor(OBDal.getInstance().get(EmesColor.class, bom.get("emes_color_id")));
			}
			if(bom.get("is_need") != null && "Y".equals(bom.get("is_need").toString())){
				if (bom.get("emes_size_id") != null) {
					manuBom.setEmesSize(OBDal.getInstance().get(EmesSize.class, bom.get("emes_size_id")));
				}
			}

			if (bom.get("emes_shape_id") != null) {
				manuBom.setEmesShape(OBDal.getInstance().get(EmesShape.class, bom.get("emes_shape_id")));
			}
			if (bom.get("Wms_Sales_Order_Info_id") != null) {
				manuBom.setWmsSalesOrderInfo(OBDal.getInstance().get(WmsSalesOrderInfo.class, bom.get("Wms_Sales_Order_Info_id")));
			}

			manuBom.setQty(new BigDecimal(bom.get("qty").toString()));
			manuBom.setUom(OBDal.getInstance().get(UOM.class, bom.get("c_uom_id")));

			OBDal.getInstance().save(manuBom);
		}
	}

	/**
	 * 生成生产订单DIY
	 */
	private void createManuOrderDiy(EmespPlanOrder planOrder, EmesoManuOrder manuOrder) {
		List<Map<String, Object>> bomList = this.getPlanOrderDiyList(planOrder.getId());
		EmesoManuOrderDiy manuDiy = null;

		for (Map<String, Object> bom : bomList) {
			manuDiy = new EmesoManuOrderDiy();
			manuDiy.setEmesoManuOrder(manuOrder);
			manuDiy.setFootType(bom.get("foot_type").toString());

			if ( bom.get("emes_component_id") != null) {
				manuDiy.setEmesComponent(OBDal.getInstance().get(EmesComponent.class, bom.get("emes_component_id")));
			}

			if ( bom.get("emes_color_id") != null) {
				manuDiy.setEmesColor(OBDal.getInstance().get(EmesColor.class, bom.get("emes_color_id")));
			}
			if ( bom.get("emes_font_id") != null) {
				manuDiy.setEmesFont(OBDal.getInstance().get(EmesFont.class, bom.get("emes_font_id")));
			}

			manuDiy.setFontSize((String)bom.get("font_size"));
			manuDiy.setFontText((String)bom.get("font_text"));
			manuDiy.setPicPath((String)bom.get("pic_path"));
			manuDiy.setIconPath((String)bom.get("icon_path"));
			manuDiy.setType((String)bom.get("type"));

			OBDal.getInstance().save(manuDiy);
		}
	}
	/**
	 * 生成生产订单工艺路线
	 */
	private void createManuOrderProcess(EmespPlanOrder planOrder, EmesoManuOrder manuOrder) {
		List<Map<String, Object>> bomList = this.getPlanOrderProcessList(planOrder.getId());
		EmesoManuOrderProcess manuProcess = null;

		Boolean OK = null;
		for (Map<String, Object> bom : bomList) {
			manuProcess = new EmesoManuOrderProcess();
			manuProcess.setEmesoManuorder(manuOrder);
			manuProcess.setEmesProcess(OBDal.getInstance().get(EmesProcess.class , bom.get("GXID")));
			manuProcess.setRouteNo(new BigDecimal(bom.get("GXNUMS").toString()).longValue());
			manuProcess.setRouteName((String) bom.get("GXNAMES"));
			if(bom.get("ISOK") != null && !bom.get("ISOK").equals("") && !bom.get("ISOK").equals("null")){
				if(bom.get("ISOK").equals("N")){
					OK = false;
				}else if(bom.get("ISOK").equals("Y")){
					OK = true;
				}
				manuProcess.setQuality(OK);
			}

			manuProcess.setNextRouteNo(new BigDecimal(bom.get("NEXTGXNUMS").toString()).longValue());

			OBDal.getInstance().save(manuProcess);
		}
	}

	/**
	 * 生成生产订单左右脚信息
	 */
	private void createManuOrderJobPlan(EmespPlanOrder planOrder, EmesoManuOrder manuOrder) {
		List<Map<String, Object>> bomList = this.getPlanOrderJobPlanList(planOrder.getId());
		EmesoJobPlan manuJobPlan = null;
		BigDecimal foot_lengths = null;
		BigDecimal foot_widths = null;
		BigDecimal foot_heights = null;
		String SIZEIDs = null;
		String xuantouIDs = null;
		for (Map<String, Object> bom : bomList) {

			manuJobPlan = new EmesoJobPlan();
			manuJobPlan.setEmesoManuorder(manuOrder);
			if( bom.get("foot_length") != null &&  !bom.get("foot_length").equals("null") &&  !bom.get("foot_length").equals("") ){
				foot_lengths = new BigDecimal(bom.get("foot_length").toString());
				manuJobPlan.setFootLength((foot_lengths) );
			}

			if( bom.get("foot_width") != null &&  !bom.get("foot_width").equals("null") &&  !bom.get("foot_width").equals("") ){
				foot_widths = new BigDecimal(bom.get("foot_width").toString());
				manuJobPlan.setFootWidth((foot_widths) );
			}

			if( bom.get("foot_height") != null &&  !bom.get("foot_height").equals("null") &&  !bom.get("foot_height").equals("") ){
				foot_heights = new BigDecimal(bom.get("foot_height").toString());
				manuJobPlan.setFootHeight((foot_heights) );
			}


			if( bom.get("SIZEID") != null &&  !bom.get("SIZEID").equals("null") &&  !bom.get("SIZEID").equals("") ){
				SIZEIDs = bom.get("SIZEID").toString();
				manuJobPlan.setEmesSize(OBDal.getInstance().get(EmesSize.class , SIZEIDs));
			}

			manuJobPlan.setType( bom.get("type").toString());
			manuJobPlan.setXuantouType( bom.get("xuantou_type").toString());

			if( bom.get("xuantou_id") != null &&  !bom.get("xuantou_id").equals("null") &&  !bom.get("xuantou_id").equals("") ){
				xuantouIDs = bom.get("xuantou_id").toString();
				manuJobPlan.setXuantou(OBDal.getInstance().get(Product.class , xuantouIDs));
			}

			OBDal.getInstance().save(manuJobPlan);
		}
	}

	/**
	 * 获取计划订单BOM列表(左右脚用量汇总)
	 * @param planOrderId
	 * @return
	 */
	private List<Map<String, Object>> getPlanOrderBomList(String planOrderId) {
		String sql = "select b.m_product_id, b.emes_size_id, b.emes_color_id,     " +
				"      b.emes_component_id, sum(b.qty) qty, b.c_uom_id , b.emes_shape_id   ,fl.is_need  " +
				"       from emesp_planorder_bom b, emesp_planorder_foot f, m_product wl  ,m_product_category fl   " +
				"      where b.emesp_planorder_foot_id = f.emesp_planorder_foot_id    " +
				"      and b.m_product_id = wl.m_product_id  " +
				"      and wl.m_product_category_id = fl.m_product_category_id  " +
				"      and f.emesp_planorder_id = ?  " +
				"      group by b.m_product_id, b.emes_size_id, b.emes_color_id,     " +
				"       b.emes_component_id, b.c_uom_id , b.emes_shape_id   ,fl.is_need  ";
		return HibernateDao.query(sql, planOrderId);
	}
	/**
	 * 获取计划订单DIV列表(左右脚用量汇总)
	 * @param planOrderId
	 * @return
	 */
	private List<Map<String, Object>> getPlanOrderDiyList(String planOrderId) {
		String sql = "select d.emes_component_id, d.emes_font_id, d.emes_color_id, d.font_text, d.pic_path,  " +
				"   d.icon_path, d.type,d.position, d.description,f.type foot_type  " +
				"  from emesp_planorder_diy d, emesp_planorder_foot f  " +
				" where d.emesp_planorder_foot_id = f.emesp_planorder_foot_id  " +
				"   and f.emesp_planorder_id = ?";
		return HibernateDao.query(sql, planOrderId);
	}

	/**
	 * 获取计划订单工艺路线列表(左右脚用量汇总)
	 * @param planOrderId
	 * @return
	 */
	private List<Map<String, Object>> getPlanOrderProcessList(String planOrderId) {
		String sql = "SELECT  " +
				"   gx.route_no AS GXNUMS,  " +
				"   gx.NAME AS GXNAMES,  " +
				"   gx.emes_process_id GXID,  " +
				"   pro.is_quality AS ISOK,  " +
				"   gx.route_no + 10 AS NEXTGXNUMS   " +
				"FROM  " +
				"   emesp_planorder_process pro,  " +
				"   emes_process gx   " +
				"WHERE  " +
				"   pro.emes_process_id = gx.emes_process_id   " +
				"   AND pro.emesp_planorder_id = ? ";
		return HibernateDao.query(sql, planOrderId);
	}

	/**
	 * 获取计划订单左右脚信息列表(左右脚用量汇总)
	 * @param planOrderId
	 * @return
	 */
	private List<Map<String, Object>> getPlanOrderJobPlanList(String planOrderId) {
		String sql = " select type , foot_length ,foot_width,foot_height,emes_size_id as SIZEID , xuantou_type,xuantou_id " +
				" from Emesp_PlanOrder_Foot " +
				" where emesp_planorder_id =  ? ";
		return HibernateDao.query(sql, planOrderId);
	}
}
